using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Security.Policy;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;

namespace LoginManager
{
    public partial class Form1 : Form
    {
        private List<LoginInfo> loginInfos = new List<LoginInfo>();
        private readonly string dataFile = "logins.json";

        public Form1()
        {
            InitializeComponent();
            LoadData();
            SetupUI();
        }

        private void LoadData()
        {
            if (File.Exists(dataFile))
            {
                var json = File.ReadAllText(dataFile);
                loginInfos = JsonConvert.DeserializeObject<List<LoginInfo>>(json) ?? new List<LoginInfo>();
            }
        }

        private void SaveData()
        {
            var json = JsonConvert.SerializeObject(loginInfos, Newtonsoft.Json.Formatting.Indented);
            File.WriteAllText(dataFile, json);
        }

        private void SetupUI()
        {
            // 控件初始化代码
            // 请确保在窗体设计器中创建以下控件：
            // ComboBox cbRemarks
            // TextBox tbUrl, tbUsername, tbPassword
            // Button btnCopyUrl, btnCopyUser, btnCopyPass, btnDelete
            // TextBox tbInput
            // Button btnParse

            // 绑定下拉框
            UpdateRemarks();

            // 按钮点击事件
            btnCopyUrl.Click += (s, e) => CopyToClipboard(tbUrl.Text);
            btnCopyUser.Click += (s, e) => CopyToClipboard(tbUsername.Text);
            btnCopyPass.Click += (s, e) => CopyToClipboard(tbPassword.Text);
            btnDelete.Click += DeleteEntry;
            btnParse.Click += ParseInput;

            // 调整按钮外观
            btnCopyUrl.Size = new Size(100, 40);
            btnCopyUrl.Font = new Font(btnCopyUrl.Font.FontFamily, 10);

            btnCopyUser.Size = new Size(100, 40);
            btnCopyUser.Font = new Font(btnCopyUser.Font.FontFamily, 10);

            btnCopyPass.Size = new Size(100, 40);
            btnCopyPass.Font = new Font(btnCopyPass.Font.FontFamily, 10);

            btnDelete.Size = new Size(100, 40);
            btnDelete.Font = new Font(btnDelete.Font.FontFamily, 10);

            btnParse.Size = new Size(100, 40);
            btnParse.Font = new Font(btnParse.Font.FontFamily, 10);

            // 下拉框选择事件
            cbRemarks.SelectedIndexChanged += (s, e) =>
            {
                if (cbRemarks.SelectedIndex >= 0)
                {
                    var info = loginInfos[cbRemarks.SelectedIndex];
                    tbUrl.Text = info.Url;
                    tbUsername.Text = info.Username;
                    tbPassword.Text = info.Password;
                }
            };
        }

        private void UpdateRemarks()
        {
            cbRemarks.Items.Clear();
            foreach (var info in loginInfos)
            {
                cbRemarks.Items.Add(info.Remark);
            }
            if (cbRemarks.Items.Count > 0) cbRemarks.SelectedIndex = 0;
        }

        private void CopyToClipboard(string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                Clipboard.SetText(text);

                // 显示自动关闭的提示
                var toast = new AutoCloseMessageBox("复制成功");
                toast.Show(); // 使用 Show() 显示窗口
            }
        }

        private void DeleteEntry(object sender, EventArgs e)
        {
            if (cbRemarks.SelectedIndex >= 0)
            {
                loginInfos.RemoveAt(cbRemarks.SelectedIndex);
                SaveData();
                UpdateRemarks();
                ClearFields();
            }
        }

        private void ClearFields()
        {
            tbUrl.Clear();
            tbUsername.Clear();
            tbPassword.Clear();
        }

        private void ParseInput(object sender, EventArgs e)
        {
            var input = tbInput.Text;
            var newInfo = new LoginInfo();

            // 解析URL、用户名和密码
            foreach (var line in input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var trimmedLine = line.Trim(); // 去除行首尾空格

                // 匹配URL
                if ((trimmedLine.Contains("外网") || trimmedLine.Contains("外部")) && trimmedLine.Contains("http"))
                {
                    var match = Regex.Match(trimmedLine, @"http[s]?://\S+");
                    if (match.Success) newInfo.Url = match.Value.Trim();
                }

                // 匹配用户名
                if ((trimmedLine.Contains("username:") || trimmedLine.Contains("面板用户:")) && string.IsNullOrEmpty(newInfo.Username))
                {
                    var match = Regex.Match(trimmedLine, @"[a-zA-Z0-9]+$");
                    if (match.Success) newInfo.Username = match.Value.Trim();
                }

                // 匹配密码
                if ((trimmedLine.Contains("password:") || trimmedLine.Contains("面板密码:")) && string.IsNullOrEmpty(newInfo.Password))
                {
                    var match = Regex.Match(trimmedLine, @"[a-zA-Z0-9]+$");
                    if (match.Success) newInfo.Password = match.Value.Trim();
                }
            }

            // 验证数据
            if (string.IsNullOrEmpty(newInfo.Url) ||
                !IsValidCredential(newInfo.Username) ||
                !IsValidCredential(newInfo.Password))
            {
                MessageBox.Show("数据解析失败，请检查输入格式");
                return;
            }

            // 获取备注
            using (var inputDialog = new InputDialog("请输入备注"))
            {
                if (inputDialog.ShowDialog() == DialogResult.OK)
                {
                    newInfo.Remark = inputDialog.InputText;
                    loginInfos.Add(newInfo);
                    SaveData();
                    UpdateRemarks();
                    tbInput.Clear();
                    // 显示自动关闭的提示
                    var toast = new AutoCloseMessageBox("保存成功");
                    toast.Show(); // 使用 Show() 显示窗口
                }
            }
        }

        private bool IsValidCredential(string input)
        {
            return Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");
        }
    }

    public class InputDialog : Form
    {
        public string InputText => tbInput.Text;
        private TextBox tbInput = new TextBox();

        public InputDialog(string prompt)
        {
            InitializeDialog(prompt);
        }

        private void InitializeDialog(string prompt)
        {
            this.Text = "输入备注";
            this.Size = new Size(300, 150);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;

            var label = new Label { Text = prompt, Top = 20, Left = 20 };
            tbInput = new TextBox { Top = 50, Left = 20, Width = 240 };
            var btnOk = new Button { Text = "确定", DialogResult = DialogResult.OK, Top = 80, Left = 120 };

            this.Controls.Add(label);
            this.Controls.Add(tbInput);
            this.Controls.Add(btnOk);

            this.AcceptButton = btnOk;
        }
    }
}
